using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using CommerceOne.Domains.IRepositories;
using CommerceOne.Models.Entities;
namespace CommerceOne.Domains.SqlRepositories
{
    public class SqlContactRepository : SqlRepositoryBase, IContactRepository
    {
        #region Singleton Instance
        private static SqlContactRepository _instance;
        public static SqlContactRepository Instance
        {
            get { return _instance ?? (_instance = new SqlContactRepository()); }
        }
        #endregion

        public void Insert(Contact contact)
        {
            contact.ModifiedDate = DateTime.Now;
            contact.Active = true;
            contact.PasswordSalt = "abcde12345";
            this.SqlContext.Contacts.Add(contact);
            int result = this.SqlContext.SaveChanges();
            if (result == 0) throw  new Exception("Contact Entity: None row inserted.");
        }

        public Contact GetByEmail(string email, bool? isActive)
        {
            if (!isActive.HasValue)
            {
                var contact = this.SqlContext.Contacts.FirstOrDefault(x => x.EmailAddress.Equals(email, StringComparison.OrdinalIgnoreCase));
                return contact;
            }

            var contactWithActiveMode = this.SqlContext.Contacts.FirstOrDefault(x => x.EmailAddress.Equals(email, StringComparison.OrdinalIgnoreCase) && x.Active == isActive.Value);
            return contactWithActiveMode;

        }

        public Boolean IsEmailExisted(string email)
        {
            return this.SqlContext.Contacts.Any(x => x.EmailAddress.Equals(email, StringComparison.OrdinalIgnoreCase));
        }
    }
} 
